package com.pc.cloud.core;

import com.pc.cloud.services.SearchArgs;
import com.pc.cloud.services.SearchResults;
import it.sauronsoftware.cron4j.Scheduler;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;

import java.io.IOException;
import java.util.Collection;

public class LuceneSearchManager implements SearchManager {
	private LuceneIndexer indexer;
	private LuceneSearcher searcher;
	private LuceneSettings settings;
	private Scheduler s = new Scheduler();

	public LuceneSettings getSettings() {
		return settings;
	}

	public void setSettings(LuceneSettings settings) {
		this.settings = settings;
	}

	public void init() throws Exception {
		searcher = new LuceneSearcher(settings);
		indexer = new LuceneIndexer(settings);
		indexer.watchNewDocuDocumentAdded(searcher);

		new Thread(new NotifyWorker()).start();
	}

	public void close() throws Exception {
		this.s.stop();
	}

	public void removeLockFile() throws Exception {
		try {
			if (IndexWriter.isLocked(this.settings.directory())) {
				IndexWriter.unlock(this.settings.directory());
			}
		} catch (IOException e) {
			throw e;
		}
	}

	public void notifyNewDocumentAdded() throws Exception {
		this.indexer.notifyNewDocumentAdded();
	}

	public void commit() throws Exception {
		this.indexer.commit();
	}

	public void createIndex(Document doc) throws Exception {
		this.indexer.createIndex(doc);
	}

	public SearchResults search(SearchArgs args) throws Exception {
		SearchResults results = this.searcher.search(args);
		return results;
	}

	public void delete(String id) throws Exception {
		this.indexer.delete(id);
	}

	public void createIndex(Collection<Document> docs, Collection<String> ids)
			throws Exception {
		this.indexer.createIndex(docs, ids);
	}

	public void delete(Collection<String> ids) throws Exception {
		this.indexer.delete(ids);
	}

	class NotifyWorker implements Runnable {

		public NotifyWorker() {
		}

		public void run() {
			while (true) {
				try {
					Thread.sleep(5000);
					indexer.notifyNewDocumentAdded();
				} catch (Throwable t) {
					t.printStackTrace();
				}
			}
		}
	}
}
